package service

import (
	"context"
	"golang.org/x/crypto/bcrypt"
	"mall-admin-go/dao"
	"mall-admin-go/model"
	"mall-admin-go/pkg/e"
	"mall-admin-go/pkg/util"
	"mall-admin-go/serializer"
)

type AdminService struct {
	UserName  string `form:"username"`
	PassWord  string `form:"password"`
	Email     string `form:"email"`
	FullName  string `form:"fullname"`
	Role      string `form:"role"`
	Mobile    string `form:"mobile"`
	AvatarUrl string `form:"avatar"`
	Status    string `form:"status"`
	CreatedAt int64  `form:"create"`
	model.BasePage
}

func (service *AdminService) AdminLogin(ctx context.Context) interface{} {
	if len(service.UserName) == 0 || len(service.UserName) > 20 {
		return serializer.ErrorResponse(e.InvalidParams)
	}

	//查询用户
	adminDao := dao.NewAdminDao(ctx)
	admin, err := adminDao.GetAdminByUsername(service.UserName)
	if err != nil {
		return serializer.ErrorResponse(e.ErrorExistUserNotFound)
	}

	//密码解密
	password, err := util.DecryptPassword(service.PassWord)
	if err != nil {
		return serializer.ErrorResponse(e.ErrorUserPassWordDecrypt)
	}
	//密码对比
	err = bcrypt.CompareHashAndPassword([]byte(admin.PasswordDigest), []byte(password))
	if err != nil {
		return serializer.ErrorResponse(e.ErrorNotCompare)
	}

	//分发token
	token, err := util.GenerateToken(admin.Uuid, admin.UserName, 0)
	if err != nil {
		return serializer.ErrorResponse(e.Error)
	}

	err = adminDao.UpdateAdminToken(token, admin.Uuid)
	if err != nil {
		return serializer.ErrorResponse(e.Error)
	}

	return serializer.AdminLoginResponse(admin, token)
}

func (service *AdminService) AdminList(ctx context.Context) interface{} {
	adminDao := dao.NewAdminDao(ctx)
	if service.PageNum == 0 || service.PageNum < 1 {
		service.PageNum = 1
	}
	if service.PageSize > 15 {
		service.PageNum = 15
	}
	//筛选条件
	conditions := make(map[string]interface{})
	if service.UserName != "" {
		conditions["user_name"] = service.UserName
	}
	if service.Mobile != "" {
		conditions["mobile"] = service.Mobile
	}
	if service.Status != "" {
		conditions["status"] = service.Status
	}
	//根据时间查询
	if service.CreatedAt != 0 {
		StartDay, EndDay := util.GetDateDay(service.CreatedAt)
		admins, total, err := adminDao.GetAdminsByDate(conditions, service.BasePage, StartDay, EndDay)
		if err != nil {
			return serializer.ErrorResponse(e.Error)
		}
		return serializer.BuildListResponse(serializer.BuildAdmins(admins), uint(total), service.PageNum, service.PageSize)
	}

	admins, total, err := adminDao.GetAdmins(conditions, service.BasePage)
	if err != nil {
		return serializer.ErrorResponse(e.Error)
	}
	return serializer.BuildListResponse(serializer.BuildAdmins(admins), uint(total), service.PageNum, service.PageSize)
}
